﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HTTT.Bussiness;
using HTTT.DataAccess;
using HTTT.AD;
using System.Configuration;
using HTTT.Utilities;

namespace HTTT.admin.adgroup
{

    public partial class ModifyMemberGroup : System.Web.UI.Page
    {
        /// <summary>
        ///  View State Username
        /// </summary>
        private Guid GroupID
        {
            get
            {
                object obj = this.ViewState["_GroupID"];
                if (obj == null)
                    return Guid.NewGuid(); //default to show ID : 0 
                else
                    return (Guid)obj;
            }
            set
            {
                this.ViewState["_GroupID"] = value;
            }

        }

        /// <summary>
        ///  List members
        /// </summary>
        private List<MyGroupMember> MemberList
        {
            get;
            set;

        }

        private void SetMemberList2ViewState()
        {
            ViewState.Add("_MemberList", MemberList.ToArray());
        }

        private void GetMemberListFromViewState()
        {
            MyGroupMember[] newArray = (MyGroupMember[])this.ViewState["_MemberList"];

            if (newArray == null)
            {
                MemberList = new List<MyGroupMember>();
            }
            else
            {
                MemberList = new List<MyGroupMember>(newArray);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["keyword"] != null)
                {
                    txtKeyword.Text = Session["keyword"].ToString();
                }
                CheckPermission();
                LoadData();
            }
        }

        private void CheckPermission()
        {
            if (!Page.User.IsInRole(Constants.ROLE_SUPER_ADMINISTRATOR)
                 && !Page.User.IsInRole(Constants.ROLE_ADMINISTRATOR))
            {
                Response.Redirect("/admin/AccessDenied.aspx");
            }
        }

        private void LoadData()
        {
            string TempID = Request.QueryString["ID"];
            Guid MyID;
            bool convert = Guid.TryParse(TempID, out MyID);
            HT_GroupsBO UserBO = new HT_GroupsBO();
            if (convert)
            {
                // Load group detail
                GroupID = MyID;
                string ouPath = LoadGroupDetail(GroupID);
                LoadOUToDDL(ddlOUGroupDetail, ouPath);

                //Load search user section
                string selectedValue = "";
                if (Session["oupath"] != null)
                {
                    selectedValue = Session["oupath"].ToString();
                }
                //Bind OU list
                LoadOUToDDL(ddlOUSearch, selectedValue);
                DoSearch();


            }
            else
            {
                Response.Redirect("GroupList.aspx");
            }
        }


        private void BindMemberList()
        {
            if (MemberList != null)
            {
                var data = from m in MemberList
                           where (m.Action != GROUP_MEM_ACTION.REMOVE)
                           select m.User;
                rptMembers.DataSource = data;
                rptMembers.DataBind();
            }

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string KeyWord = txtKeyword.Text.Trim();
            if (KeyWord == string.Empty)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg("Phải nhập từ khóa tìm kiếm!"), true);
                return;
            }
            DoSearch();
        }
        private void DoSearch()
        {
            string KeyWord = txtKeyword.Text.Trim();
            if (KeyWord == string.Empty)
            {
                return;
            }
            string OUPath = ddlOUSearch.SelectedValue;
            Session["keyword"] = KeyWord;
            Session["oupath"] = OUPath;
            HT_UserBO BO = new HT_UserBO();
            IEnumerable<HT_User> ListData = BO.SearchUser(KeyWord, OUPath);
            if (ListData == null)
            {
                lblMsg.Text = "Không tìm thấy kết quả !";
                return;
            }
            rptUserSearch.DataSource = ListData;
            rptUserSearch.DataBind();
        }


        protected void btnClear_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadOUToDDL(DropDownList ddl, string selectedValue)
        {
            //Get OU list
            HT_OUBO Bo = new HT_OUBO();
            List<HT_OU> ListBO = Bo.GetAllHT_OU().ToList();
            ddl.DataSource = ListBO;
            ddl.DataValueField = ADOUProperties.DISTINGUISHEDNAME;
            ddl.DataTextField = ADOUProperties.NAME;
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("▼ " + ConfigurationManager.AppSettings["LDAPDomain"], ConfigurationManager.AppSettings["DomainPath"]));
            ddl.SelectedValue = selectedValue;
        }
        private string LoadGroupDetail(Guid id)
        {
            //Get UserInfo by username
            HT_GroupsDAO dao = new HT_GroupsDAO();
            HT_Groups Info = dao.GetHT_GroupsByID(id);
            txtName.Text = Info.name;
            txtDescription.Text = Info.description;
            rblGroupScope.SelectedValue = Info.groupScope.ToString();
            rblGroupType.SelectedValue = Convert.ToInt16(Info.isSecurityGroup).ToString();
            SetReadOnly(true);
            BuildListMember(Info.ID, Info.members);
            BindMemberList();
            string ouPath = Info.LDAPPath;
            ouPath = ouPath.Substring(ouPath.IndexOf(',') + 1);
            return ouPath;
        }

        private void BuildListMember(Guid groupId, string members)
        {
            MemberList = new List<MyGroupMember>();
            string[] MemArr = members.Split(Constants.MEMBERSPLIT);
            foreach (string mem in MemArr)
            {
                HT_UserBO UserBO = new HT_UserBO();
                HT_User CurrentUser = UserBO.GetHT_UserByUsername(mem);
                if (CurrentUser != null)
                {
                    MemberList.Add(new MyGroupMember(groupId, CurrentUser, GROUP_MEM_ACTION.NONE));
                }
            }
            SetMemberList2ViewState();
        }

        private void SetReadOnly(bool IsReadOnly)
        {
            txtName.ReadOnly = IsReadOnly;
            txtDescription.ReadOnly = IsReadOnly;
            ddlOUGroupDetail.Enabled = !IsReadOnly;
            rblGroupScope.Enabled = !IsReadOnly;
            rblGroupType.Enabled = !IsReadOnly;
        }
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                if (SaveForm())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatMsgThenRedirect("Tạo yêu cầu sửa thành viên thành công", "GroupList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }

        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("GroupList.aspx");
        }


        private ReturnValue<bool> ValidateData()
        {
            if (txtFromRequest.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập thông tin yêu cầu");
            return new ReturnValue<bool>(true, "");
        }


        private bool SaveForm()
        {
            //Collec infomation
            HT_Request NewRequest = new HT_Request();
            HT_GroupsBO groupBO = new HT_GroupsBO();
            NewRequest.ID = Guid.NewGuid();
            NewRequest.Action = HT_ACTION.EDIT_GROUP_MEMBER.ToString();
            // Prepare list added user data and remove user data
            List<string> AddList = new List<string>();
            List<string> RemoveList = new List<string>();
            GetMemberListFromViewState();
            foreach (MyGroupMember mem in MemberList)
            {
                if (mem.Action == GROUP_MEM_ACTION.ADD)
                {
                    AddList.Add(mem.User.sAMAccountName);
                }
                if (mem.Action == GROUP_MEM_ACTION.REMOVE)
                {
                    RemoveList.Add(mem.User.sAMAccountName);
                }
            }

            NewRequest.ActionDescription = groupBO.BuildEditGroupMemberString(txtName.Text, AddList, RemoveList);
            NewRequest.ActionName = "Sửa thành viên Group  <strong>" + txtName.Text + "</strong>";
            NewRequest.Status = Utilities.HT_REQUESTSTATUS.PEDDING.ToString();
            NewRequest.Note = txtFromRequest.Text.Trim();
            NewRequest.RequestDate = DateTime.Now;
            NewRequest.Requestedby = Page.User.Identity.Name;
            HT_RequestBO re = new HT_RequestBO();
            Boolean result = re.InsertRequest(NewRequest);
            return result;
        }

        protected void rptMembers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Remove2Group")
            {
                string username = "";
                foreach (Control c in rptMembers.Items[e.Item.ItemIndex].Controls)
                {
                    if (typeof(HiddenField) == c.GetType())
                    {
                        HiddenField hfValue = (HiddenField)c;
                        username = hfValue.Value;
                        break;
                    }
                }
                RemoveUser(username);
            }
        }

        private void RemoveUser(string username)
        {
            GetMemberListFromViewState();
            foreach (MyGroupMember item in MemberList)
            {
                if (item.User.sAMAccountName == username)
                {
                    item.Action = GROUP_MEM_ACTION.REMOVE;
                    break;
                }
            }
            // Bind memberlsit again
            BindMemberList();
            SetMemberList2ViewState();
        }

        protected void rptUserSearch_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Add2Group")
            {
                string username = "";
                foreach (Control c in rptUserSearch.Items[e.Item.ItemIndex].Controls)
                {
                    if (typeof(HiddenField) == c.GetType())
                    {
                        HiddenField hfValue = (HiddenField)c;
                        username = hfValue.Value;
                        break;
                    }
                }
                AddUser2Group(username);
            }

        }

        private void AddUser2Group(string username)
        {
            GetMemberListFromViewState();
            bool exist = false;
            foreach(MyGroupMember mem in MemberList)
            {
                //Check exist memeber
                if(mem.User.sAMAccountName == username)
                {
                    exist = true;
                    //If status is remove then add again
                    if(mem.Action == GROUP_MEM_ACTION.REMOVE)
                    {
                        mem.Action = GROUP_MEM_ACTION.ADD;
                    }
                    else
                    {
                        //Else warning
                        ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatAlertMsg(username + " đã tồn tại trong group"), true);
                        return;
                    }
                    break;
                }
            }

            if(!exist)
            {
                HT_UserBO UserBO = new HT_UserBO();
                HT_User AddUser = UserBO.GetHT_UserByUsername(username);
                MemberList.Add(new MyGroupMember(GroupID, AddUser, GROUP_MEM_ACTION.ADD));
            }
            // Bind memberlsit again
            BindMemberList();
            SetMemberList2ViewState();
        }
    }
}